<?php

namespace app\common\library;

use app\admin\model\Score;
use app\common\model\Config;

class HandleScoreService
{

    private $config;
    const ACTION_FIELD = [
        1 => 'register',
        2 => 'post',
        3 => 'comment',
        4 => 'forward',
        5 => 'collect',
        6 => 'essence',
        7 => 'top',
        8 => 'be_collect',
        9 => 'be_forward',
        10 => 'download',
    ];

    public function __construct()
    {
        $this->config = $this->getConfig();
    }

    private function getConfig()
    {
        $score_config = Config::where('group', 'score_config')->column('value', 'name');
        if (!count($score_config)) {
            return $this->initData();
        } else {
            return $score_config;
        }
    }

    private function initData()
    {
        // 初始化数据
        $config_status = Config::where('name', 'configgroup')->value('value');
        $config_status = json_decode($config_status, true);
        if (!array_key_exists('score_config', $config_status)) {
            $config_status['score_config'] = '积分配置';
            Config::where('name', 'configgroup')->update([
                'value' => json_encode($config_status)
            ]);
        }
        // 初始化积分配置数据
        $base_vip = config('score_config');
        foreach ($base_vip['add_rule'] as $k => $v) {
            Config::create([
                'name' => $k,
                'group' => 'score_config',
                'title' => $v['name'] . '增加积分',
                'tip' => $v['name'] . '增加积分',
                'type' => "string",
                'value' => $v['score']
            ]);
        }
        // 初始化扣减积分数据
        foreach ($base_vip['reduce_rule'] as $k => $v) {
            Config::create([
                'name' => $k,
                'group' => 'score_config',
                'title' => $v['name'] . '扣减积分',
                'tip' => $v['name'] . '扣减积分',
                'type' => "string",
                'value' => $v['score']
            ]);
        }
        // 初始化积分发放上限数据
        foreach ($base_vip['max_add_rule'] as $k => $v) {
            Config::create([
                'name' => $k . '_max_score',
                'group' => 'score_config',
                'title' => $v['name'],
                'tip' => $v['name'] . '积分发放上限',
                'type' => "string",
                'value' => $v['max_score']
            ]);
        }
        return Config::where('group', 'score_config')->column('value', 'name');
    }

    public function getScore($type, $action, $uid)
    {
        $rule = config('score_config.max_add_rule')[$type]['rule'];
        if (in_array($action, $rule)) {
            $max_score = $this->config[$type . '_max_score'] ?? 0;
            $today_max = Score::where('user_id', $uid)
                ->where('change_time', '>', strtotime(date('Y-m-d')))
                ->where('change_time', '<', strtotime(date('Y-m-d')) + 86400)
                ->where('seq_flag', 1)
                ->where(function ($q) use ($type) {
                    if ($type == 'add_rule') {
                        $q->whereIn('change_type', [3, 4, 5]);
                    } else {
                        $q->whereIn('change_type', [8, 9]);
                    }
                })
                ->sum('change_num');

            if ($today_max >= $max_score) {
                return 0;
            }
        } else {
            return 0;
        }
        return $this->config[$action] ?? 0;
    }

    /**
     * 保存积分记录
     * @param $action 1注册 2发帖 3评论 4转发 5收藏 6精华 7置顶 8被收藏 9被转发 10下载
     * @param $uid 用户id
     * @param $change_num  积分变动数
     * @param $rel_id 关联id
     * @param $seq_flag 1加分 2减分
     * @param $comments 备注
     * @return Score
     */
    public function setData($action, $uid, $change_num, $rel_id, $seq_flag = 1, $comments = '')
    {
        return Score::create([
            'user_id' => $uid,
            'ref_sn' => $rel_id,
            'change_type' => array_search($action, self::ACTION_FIELD),
            'change_time' => time(),
            'change_num' => $change_num,
            'seq_flag' => $seq_flag,
            'comments' => $comments
        ]);
    }
}